<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span class="active">故障报修列表</span>
    </div>

    <el-row>
      <el-col :span="3">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="关键字">
            <el-input v-model="form.key" placeholder="请输入关键字"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="3">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="地址">
            <el-input v-model="form.address" placeholder="请输入地址"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="3">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="电话">
            <el-input v-model="form.tel" placeholder="请输入电话"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="10">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="活动时间">
            <span class="demonstration">时间查询</span>
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="3">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="报修状态">
            <el-select v-model="form.state" clearable placeholder="请选择报修状态">
              <el-option
                v-for="item in stateOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="4">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="报修类型">
            <el-select v-model="form.type" clearable placeholder="请选择报修类型">
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="居民">
            <el-input v-model="form.userid" placeholder="请输入居民ID"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4" style="margin-left: 20px; margin-top: 30px;">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-col>
    </el-row>
    <el-row style="margin: 10px 0;">
      <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
    </el-row>
    <!-- 表格 -->
    <BaseTable
      :tableColumn="tableColumn"
      :tableData="tableData"
      :loading="loading"
      :isShowSelection="true"
      @edit="handleClick"
      @delete="handleDelete"
      @selection-change="handleSelectionChange"
    >
        <template #images="{ row }">
          <div v-if="row.images && row.images.length > 0">
            <el-image
              v-for="(image, index) in row.images"
              :key="index"
              :src="getImageUrl(image.url)"
              style="width: 50px; height: 50px; margin-right: 5px;"
              fit="cover"
              :preview-src-list="[getImageUrl(image.url)]"
              v-show="image.state === 2"
            ></el-image>
          </div>
          <span v-else>无图片</span>
        </template>
        <template #statename="{ row }">
          <span :class="getStateClass(row.statename)">{{ row.statename }}</span>
        </template>
        <template #options="{ row }">
          <el-button size="mini" @click="handleDelete(row)" type="danger">删除</el-button>
        </template>
    </BaseTable>
    <!-- 分页 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.page"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="query.psize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="counts"
    >
    </el-pagination>
  </el-card>
</template>
<script>
import { list, del, deleteall, stateList, typeList } from '../api/repairs'
import BaseTable from './BaseTable.vue'

export default {
  name: 'RepairsView',
  components: {
    BaseTable,
  },
  data() {
    return {
      loading: true,
      tableColumn: [
        {
          prop: 'id',
          label: 'ID',
        },
        {
          prop: 'typename',
          label: '故障类型',
        },
        {
          prop: 'address',
          label: '维修地址',
        },
        {
          prop: 'images',
          label: '故障图片',
          slotname: 'images'
        },
        {
          prop: 'content',
          label: '故障描述',
        },
        {
          prop: 'username',
          label: '业主名称',
        },
        {
          prop: 'addtime',
          label: '维修日期',
        },
        {
          prop: 'statename',
          label: '状态',
          slotname: 'statename'
        },
        {
          prop: 'options',
          label: '操作',
          slotname: 'options',
        },
      ],
      form: {
        key: '',
        address: '',
        tel: '',
        state: '',
        type: '',
        userid: ''
      },
      query: {
        page: 1,
        psize: 10,
      },
      dateRange: [],

      tableData: [],
      counts: 0,
      multipleSelection: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
      stateOptions: [],
      typeOptions: []
    }
  },
  created() {
    this.getList()
    this.getRepairStates()
    this.getRepairTypes()
  },

  methods: {
    async getList() {
      this.loading = true
      try {
        // 合并查询条件
        const params = {
          ...this.query,
          ...this.form
        }
        
        // 处理日期范围
        if (this.dateRange && this.dateRange.length === 2) {
          params.begindate = this.dateRange[0]
          params.enddate = this.dateRange[1]
        }
        
        // 处理居民ID
        if (params.userid) {
          params.userid = parseInt(params.userid)
        }

        let {
          data: { counts, list: listData },
        } = await list(params)
        this.counts = counts
        this.tableData = listData
        this.loading = false
        console.log('获取到的数据:', listData)
      } catch (error) {
        console.error('获取数据失败:', error)
        this.loading = false
      }
    },
    
    async getRepairStates() {
      try {
        const { data } = await stateList({ page: 1, psize: 100 })
        this.stateOptions = data.list
      } catch (error) {
        console.error('获取维修状态失败:', error)
      }
    },
    
    async getRepairTypes() {
      try {
        const { data } = await typeList({ page: 1, psize: 100 })
        this.typeOptions = data.list
      } catch (error) {
        console.error('获取维修类型失败:', error)
      }
    },
    
    getImageUrl(url) {
      // 如果没有提供URL，返回空字符串
      if (!url) {
        return ''
      }
      
      // 如果是完整URL直接返回
      if (url.startsWith('http') || url.startsWith('https')) {
        return url
      }
      
      // 如果是以/开头的绝对路径，直接使用
      if (url.startsWith('/')) {
        return process.env.VUE_APP_BASE_API + url
      }
      
      // 否则拼接基础URL和uploads目录
      return process.env.VUE_APP_BASE_API + '/uploads/' + url
    },
    
    getStateClass(state) {
      switch (state) {
        case '处理完成':
          return 'state-blue'
        case '正在处理':
          return 'state-red'
        case '等待处理':
          return 'state-black'
        default:
          return ''
      }
    },

    async handleDelete(row) {
      try {
        await this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        await del({ id: row.id })
        await this.getList()
        this.$message({
          type: 'success',
          message: '删除成功!',
        })
      } catch (error) {
        if (error === 'cancel') {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        } else {
          console.error('删除失败:', error)
        }
      }
    },
    
    handleClick(row) {
      console.log('编辑操作:', row)
      // 这里可以添加编辑逻辑
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    
    async handleDeleteAll() {
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请至少选择一条记录!',
        })
        return
      }

      try {
        await this.$confirm(`此操作将永久删除选中的 ${this.multipleSelection.length} 条记录, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })

        // 提取选中项的ID数组
        const ids = this.multipleSelection.map((item) => item.id)

        // 调用批量删除接口
        await deleteall({ ids })

        // 重置选择
        this.multipleSelection = []
        
        // 刷新列表
        await this.getList()

        this.$message({
          type: 'success',
          message: '批量删除成功!',
        })
      } catch (error) {
        if (error === 'cancel') {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        } else {
          console.error('批量删除失败:', error)
          this.$message({
            type: 'error',
            message: '批量删除失败!',
          })
        }
      }
    },
    
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.query.psize = val
      this.query.page = 1
      this.getList()
    },
    
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.query.page = val
      this.getList()
    },
    
    handleSearch() {
      this.query.page = 1
      this.getList()
    },
    
    handleReset() {
      this.form = {
        key: '',
        address: '',
        tel: '',
        state: '',
        type: '',
        userid: ''
      }
      this.dateRange = []
      this.query.page = 1
      this.getList()
    }
  },
}
</script>
<style lang="less">
@import '../assets/css/repairs.less';

.state-blue {
  color: #409EFF;
}

.state-red {
  color: #F56C6C;
}

.state-black {
  color: #606266;
}
</style>